package com.wtcrazy.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtcrazy.dao.UserMapper;
import com.wtcrazy.entity.*;
import com.wtcrazy.service.IUserService;
import com.wtcrazy.utils.JsonResult;
import com.wtcrazy.utils.JwtUtil;
import com.wtcrazy.utils.RandomUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

@Service//标注于Service接口的实现类上，将当前类自动注入到Spring容器中
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired//将属性注入
    private UserMapper userMapper;
    @Autowired
    private UserServiceImpl userService;
    @Autowired(required = false)//无法自动装配,找不到'JavaMailSender'类型的Bean就用这个
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.username}")//将yml里面的属性赋值给from
    private String from;


    @Override
    public JsonResult login(User user) {
        User dbUser1 = userMapper.loginUsername(user);
        User dbUser2 = userMapper.loginMail(user);
        User dbUser = (dbUser1 == null ? dbUser2 : dbUser1);
        if (dbUser != null) {//用户存在
            String token = JwtUtil.createToken(dbUser.getId());//创造token
            dbUser.setToken(token);
            return JsonResult.builder().result(dbUser).code("20000").message("登录成功！").build();
        } else {
            return JsonResult.builder().result(dbUser).code("50000").message("用户不存在").build();
        }
    }

    @Override
    public JsonResult deleteMyself(String uid) {
        List<String> result = userService.getMyPosts(uid);//获取用户的所有发布的帖子id
        for (int i = 0; i < result.size(); i++) {
            userService.deletePost(result.get(i));//列表访问
        }
        userMapper.deleteShop(uid);//用户删除自己的订单、地址、用户点赞表、用户评论表、用户表
        return JsonResult.builder().result(true).message("注销成功").code("20000").build();
    }

    @Override
    public JsonResult register(User user) {
        Integer cnt = userMapper.queryMail(user.getMail());
        Integer num = userMapper.queryUsername(user.getUsername());
        if (cnt == 1) {//该邮箱已经注册过
            return JsonResult.builder().code("50000").message("该邮箱已经注册过了").result(null).build();
        } else if (num == 1) {
            return JsonResult.builder().code("50005").message("已经有人使用这个用户名了").result(null).build();
        } else {
            user.setId(UUID.randomUUID().toString().replace("-", ""));//id用uuid做成唯一id
            if (user.getUsername() != "" && user.getMail() != "" && user.getPassword() != "" && user.getPhone() != "" && user.getNickname() != "") {
                userMapper.register(user);
            }
            return JsonResult.builder().code("20000").message("注册成功").result(user).build();
        }
    }

    @Override
    public JsonResult findPassword(Object obj) {
        userMapper.updatePassword(obj);
        return JsonResult.builder().result(obj).message("找回成功").code("20000").build();
    }

    @Override
    public String sendMailCode(String mail) {
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mailMessage);//富文本
//        SimpleMailMessage message = new SimpleMailMessage();//简单文本
        String code = RandomUtil.generateDigitalString(4);
        String content = "<h3>尊敬的用户：</h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;您获得的验证码是<b>" + code + "</b>，有效期60秒，请妥善保管，切勿泄露";
        try {
            helper.setFrom(from);//发送人,不写发送人报553错
            helper.setTo(mail);
            helper.setSentDate(new Date());
            helper.setSubject("【健康守护者系统】邮箱验证");
            helper.setText(content, true);
            javaMailSender.send(mailMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return code;
    }

    @Override
    public JsonResult checkToken(String token) {
        Integer num = JwtUtil.checkToken(token);//验证token

        if (num == 0) {
            return JsonResult.builder().result(false).message("缺失Token").code("50000").build();
        } else if (num == 1) {
            return JsonResult.builder().result(true).message("Token正确").code("20000").build();
        } else {
            return JsonResult.builder().result(false).message("Token异常或过期").code("50005").build();
        }
    }

    @Override
    public List<Object> getAllPosts() {
        List<Object> result = userMapper.getAllPosts();
        return result;
    }

    @Override
    public List<Object> getAllHotPosts() {
        List<Object> result = userMapper.getAllHotPosts();
        return result;
    }

    @Override
    public List<Object> getLimitPosts(Integer startIndex, Integer pageSize) {
        //token验证

        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex", startIndex);
        map.put("pageSize", pageSize);
        List<Object> result = userMapper.getLimitPosts(map);
        return result;
    }

    @Override
    public List<Object> getLimitHotPosts(Integer startIndex, Integer pageSize) {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("startIndex", startIndex);
        map.put("pageSize", pageSize);
        List<Object> result = userMapper.getLimitHotPosts(map);//注意这里也要改啊
        return result;
    }

    @Override
    public Post getPost(String id) {
        return userMapper.getPost(id);
    }

    @Override
    public Post uploadPost(Post post) {
        JSONArray jsonArray = JSONArray.fromObject(post.getPicsUrl());
        String result = jsonArray.toString();//result是字符串形式的列表
        post.setId(UUID.randomUUID().toString().replace("-", ""));
        post.setPublishDate(new Date().getTime());//时间戳是long类型
        post.setViewCount(1);
        post.setPicsUrl(result);
        userMapper.uploadPost(post);
        return post;
    }

    @Override
    public String deletePost(String postid) {//传的是帖子id
        userMapper.deletePostComment(postid);
        userMapper.deletePostLike(postid);//先得删除点赞帖子表
        userMapper.deletePost(postid);//删除帖子
        return postid;
    }

    @Override
    public String addPostView(String id) {//用@Requestparam接收id为null
        userMapper.addPostView(id);
        return id + "更新成功";
    }

    @Override
    public PostLike isLikePost(PostLike postLike) {
        return userMapper.isLikePost(postLike);
    }

    @Override
    public PostLike likePost(PostLike postLike) {
        postLike.setId(UUID.randomUUID().toString().replace("-", ""));
        postLike.setLikeTime(new Date().getTime());
        userMapper.likePost(postLike);
        return postLike;
    }

    @Override
    public String unLikePost(PostLike postLike) {
        userMapper.unLikePost(postLike);
        return "删除成功";
    }

    @Override
    public String updatePostLike(String jsonStr) {
        System.out.println("updatePostLike===" + jsonStr);//String类型
        JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
        userMapper.updatePostLike(obj);
        return obj + "更新成功";
    }

    @Override
    public String updatePostComment(String jsonStr) {
        JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象
        userMapper.updatePostComment(obj);
        return obj + "更新成功";
    }

    @Override
    public List<String> getMyPosts(String uid) {
        List<String> result = userMapper.getMyPosts(uid);
        return result;
    }

    @Override
    public List<Object> getLimitMyPosts(Object obj) {
        List<Object> result = userMapper.getLimitMyPosts(obj);
        return result;
    }

    @Override
    public List<Object> getLimitMyHotPosts(Object obj) {
        return userMapper.getLimitMyHotPosts(obj);
    }

    @Override
    public Object updateUserInfo(Object obj) {
        userMapper.updateUserInfo(obj);
        return obj;
    }

    @Override
    public List<PostLike> getUserAllLikePosts(Object obj) {
        return userMapper.getUserAllLikePosts(obj);
    }

    @Override
    public Comment submitComment(Comment comment) {
        comment.setId(UUID.randomUUID().toString().replace("-", ""));
        comment.setTime(new Date().getTime());
        userMapper.submitComment(comment);
        return comment;
    }

    @Override
    public List<Comment> getAllCommment(String id) {
        return userMapper.getAllCommment(id);
    }

    @Override
    public List<Comment> getAllSecondCommment(String postId, String replyCommentId) {
        return userMapper.getAllSecondCommment(postId, replyCommentId);
    }

    @Override
    public Object deleteComment(Object obj) {
        userMapper.deleteComment(obj);
        return obj;
    }

    @Override
    public void changePostComment(Object obj) {
        userMapper.changePostComment(obj);
    }

    @Override
    public List<Comment> getUserComment(Object obj) {
        return userMapper.getUserComment(obj);
    }

    @Override
    public List<Article> getLimitArticle(Integer classid, Integer start, Integer pageSize) {
        return userMapper.getLimitArticle(classid, start, pageSize);
    }

    @Override
    public Article getArticle(String id) {
        return userMapper.getArticle(id);
    }

    @Override
    public Integer querySecondCommentNum(String commentId) {
        return userMapper.querySecondCommentNum(commentId);
    }

    @Override
    public Integer getUserInfoLike(String uid) {
        return userMapper.getUserInfoLike(uid);
    }

    @Override
    public Integer getUserInfoPost(String uid) {
        return userMapper.getUserInfoPost(uid);
    }

    @Override
    public Integer getUserInfoComment(String uid) {
        return userMapper.getUserInfoComment(uid);
    }
}
